﻿using Abp;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using Abp.ObjectMapping;
using AutoMapper.QueryableExtensions;
using FwProject.Com.Dto;
using FwProject.ShopApplication;
using FwProject.ShopApplication.Configuration;
using FwProject.ShoppingMall.Com;
using FwProject.ShoppingMall.Product;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using X.PagedList;
using static FwProject.Com.Dto.SpceEnterDto;

namespace FwProject.Com
{
    /// <summary>
    /// 规格管理
    /// </summary>
    public class SpceAppService : FwProjectAppServiceBase, ISpceAppService
    {
        private readonly IRepository<Spce, Guid> _repositorySpce;
        private readonly IRepository<ProductSpcevalue, Guid> _repositoryProductSpcevalue;
        private readonly IHostingEnvironment _hostingEnvironment;
        private readonly IConfigurationRoot _appConfiguration;
       /// <summary>
       /// 
       /// </summary>
        public IGuidGenerator _guid { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public IObjectMapper _map { get; set; }
        /// <summary>
        /// 构造注入
        /// </summary>
        /// <param name="repositorySpce"></param>
        /// <param name="hostingEnvironment"></param>
        /// <param name="repositoryProductSpcevalue"></param>
        public SpceAppService(IRepository<Spce, Guid> repositorySpce, IHostingEnvironment hostingEnvironment, IRepository<ProductSpcevalue, Guid> repositoryProductSpcevalue)
        {
            _repositorySpce = repositorySpce;
            _guid = SequentialGuidGenerator.Instance;
            _hostingEnvironment = hostingEnvironment;
            _repositoryProductSpcevalue = repositoryProductSpcevalue;
            _appConfiguration= _hostingEnvironment.GetAppConfiguration();
        }

        /// <summary>
        /// 获取规格数据
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public async Task<LayerDataBaseDto> GetSpceLayerDataAsync(int page, int limit, string keyword)
        {
            var query = _repositorySpce.GetAll();

            if (!string.IsNullOrWhiteSpace(keyword))
                query = query.Where(o => o.SpceName.Contains(keyword));

            var pagelist = await query.OrderByDescending(o => o.CreationTime).ProjectTo<SpceOutputDto>().ToPagedListAsync(page, limit);

            LayerDataBaseDto dto = new LayerDataBaseDto();
            dto.Data = pagelist;
            dto.Count = pagelist.TotalItemCount;
            return dto;
        }
        /// <summary>
        /// 根据id获取dto
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<SpceEnterDto> GetEnterDtoAsync(Guid id)
        {
            var entity = await _repositorySpce.GetAsync(id);
            var parvalus = await _repositoryProductSpcevalue.GetAll().Where(o => o.ProductSpceid == id).MapTo<List<ProductSpcevalueDto>>().ToListAsync();
            var dto = entity.MapTo<SpceEnterDto>();
            dto.ProductSpcevalues = parvalus;
            return dto;
        }
        /// <summary>
        /// 创建一个规格
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>

        public async Task<Guid> CreateAsync(SpceEnterDto input)
        {
            var model = input.MapTo<Spce>();
            model.Id = _guid.Create();
            //model.Piclogo = SaveFile(_hostingEnvironment.WebRootPath, input.Piclogo, Brand.TempFileUrlPrefix, Brand.SaveFileUrlPrefix, $"{DateTime.Now.ToString("yyyyMMdd")}/");
            var id = await _repositorySpce.InsertAndGetIdAsync(model);
            if (input.ProductSpcevalues.Count > 0)
            {
                foreach (var item in input.ProductSpcevalues)
                {
                    var spvalue = item.MapTo<ProductSpcevalue>();
                    spvalue.Id = _guid.Create();
                    spvalue.ProductSpceid = id;

                    if (!string.IsNullOrEmpty(item.Spcevalueico))
                    {
                        string FileTempPath = _appConfiguration["FileServicePath:TempSpce"];
                        string FileSavaPath = _appConfiguration["FileServicePath:SavaSpce:SavaFilePath"];
                        var path = SaveFile(item.Spcevalueico, FileTempPath, FileSavaPath, $"{DateTime.Now.ToString("yyyyMMdd")}/");
                        if (!string.IsNullOrEmpty(path))
                        {
                            spvalue.Spcevalueico = _appConfiguration["FileServicePath:SavaSpce:Virtual"] + path;
                        }
                        else
                        {
                            spvalue.Spcevalueico = null;
                        }
                    }
              
                    await _repositoryProductSpcevalue.InsertAsync(spvalue);
                }
            }
            return id;
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="id"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<Guid> ModifyAsync(Guid id, SpceEnterDto input)
        {
            var model = await _repositorySpce.GetAsync(id);
            var original = await _repositoryProductSpcevalue.GetAll().Where(o => o.ProductSpceid == id).ToListAsync();

            if (input.ProductSpcevalues != null)
            {
                var proSpvalues = input.ProductSpcevalues;

                #region 参数删除
                var removes = original.Where(o => proSpvalues.Any(s => s.Id == o.Id) == false).ToList();
                if (removes.Count > 0)
                {
                    for (int i = 0; i < removes.Count; i++)
                    {
                        await _repositoryProductSpcevalue.DeleteAsync(removes[i]);
                    }
                }

                #endregion

                #region 参数增加
                var adds = proSpvalues.Where(r => original.Any(o => o.Id == r.Id) == false).ToList();
                if (adds.Count() > 0)
                {
                    foreach (var item in adds)
                    {
                        var spvalue = item.MapTo<ProductSpcevalue>();
                        spvalue.Id = _guid.Create();
                        spvalue.ProductSpceid = id;

                        if (!string.IsNullOrEmpty(item.Spcevalueico))
                        {
                            string FileTempPath = _appConfiguration["FileServicePath:TempSpce"];
                            string FileSavaPath = _appConfiguration["FileServicePath:SavaSpce:SavaFilePath"];
                            var path = SaveFile(item.Spcevalueico, FileTempPath, FileSavaPath, $"{DateTime.Now.ToString("yyyyMMdd")}/");
                            if (!string.IsNullOrEmpty(path))
                            {
                                spvalue.Spcevalueico = _appConfiguration["FileServicePath:SavaSpce:Virtual"] + path;
                            }
                            else
                            {
                                spvalue.Spcevalueico = null;
                            }
                        }

                        await _repositoryProductSpcevalue.InsertAsync(spvalue);
                    }
                }
                #endregion

                #region 参数修改
                var join = original.Join(proSpvalues, i => i.Id, j => j.Id, (i, j) => new
                {
                    i,
                    j
                });
                foreach (var item in join)
                {
                    item.i.Spcevalue = item.j.Spcevalue;

                    var originalvalue = "";
                    if (!string.IsNullOrEmpty(item.j.Spcevalueico))//判断是否传入图片
                    {
                        if (!string.IsNullOrEmpty(item.i.Spcevalueico))//判断是否原有图片
                        {
                            var l = item.i.Spcevalueico.Split('/');
                            originalvalue = l[l.Length - 1];
                        }

                        string FileTempPath = _appConfiguration["FileServicePath:TempSpce"];
                        string FileSavaPath = _appConfiguration["FileServicePath:SavaSpce:SavaFilePath"];
                        var path = SaveFile(item.j.Spcevalueico, FileTempPath, FileSavaPath, $"{DateTime.Now.ToString("yyyyMMdd")}/", originalvalue);
                        if (!string.IsNullOrEmpty(path))
                        {
                            item.i.Spcevalueico = _appConfiguration["FileServicePath:SavaSpce:Virtual"] + path;
                        }
                        else
                        {
                            item.i.Spcevalueico = null;
                        }
                    }

                    await _repositoryProductSpcevalue.UpdateAsync(item.i);
                }
                #endregion
            }

            model = input.MapTo(model);
            var entity = await _repositorySpce.UpdateAsync(model);
            return entity.Id;
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task DeleteAsync(Guid id)
        {
            var entity = await _repositorySpce.GetAsync(id);
            await _repositorySpce.DeleteAsync(entity);
        }
    }
}
